from functools import wraps
from flask import session, jsonify
from utils.logger import get_logger

logger = get_logger(__name__)

def login_required(f):
    """
    用于验证用户是否已登录的装饰器
    """
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            logger.warning("Unauthorized access attempt to protected route")
            return jsonify({
                "success": False,
                "message": "请先登录"
            }), 401
        return f(*args, **kwargs)
    return decorated_function

def get_current_user_id():
    """
    获取当前登录用户的ID
    如果用户未登录，返回None
    """
    return session.get('user_id')

def get_current_username():
    """
    获取当前登录用户的用户名
    如果用户未登录，返回None
    """
    return session.get('username')

